import sys
import os
import time
from datetime import datetime, timedelta
import subprocess
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                            QHBoxLayout, QLabel, QLineEdit, QPushButton, 
                            QRadioButton, QButtonGroup, QSystemTrayIcon, 
                            QMenu, QAction, QMessageBox)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QIcon, QFont

class ShutdownTimer(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("定时关机")
        self.setFixedSize(350, 280)
        
        # 系统托盘设置
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(QIcon("icon.ico"))  # 需要有一个icon.ico文件在同目录下
        
        # 托盘菜单
        tray_menu = QMenu()
        show_action = QAction("显示", self)
        quit_action = QAction("退出", self)
        cancel_action = QAction("取消关机", self)
        
        show_action.triggered.connect(self.show)
        quit_action.triggered.connect(self.close_app)
        cancel_action.triggered.connect(self.cancel_shutdown)
        
        tray_menu.addAction(show_action)
        tray_menu.addAction(cancel_action)
        tray_menu.addAction(quit_action)
        
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.activated.connect(self.tray_icon_activated)
        self.tray_icon.show()
        
        # 主界面设置
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(self.central_widget)
        main_layout.setSpacing(10)
        main_layout.setContentsMargins(20, 20, 20, 20)
        
        # 设置字体
        title_font = QFont()
        title_font.setBold(True)
        title_font.setPointSize(11)
        
        normal_font = QFont()
        normal_font.setPointSize(10)
        
        # 标题
        title_label = QLabel("Windows 定时关机工具")
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignCenter)
        main_layout.addWidget(title_label)
        
        # 选择模式
        mode_layout = QHBoxLayout()
        self.mode_group = QButtonGroup(self)
        
        self.countdown_radio = QRadioButton("倒计时关机")
        self.specific_radio = QRadioButton("指定时间关机")
        
        self.countdown_radio.setFont(normal_font)
        self.specific_radio.setFont(normal_font)
        
        self.countdown_radio.setChecked(True)
        
        self.mode_group.addButton(self.countdown_radio, 1)
        self.mode_group.addButton(self.specific_radio, 2)
        
        mode_layout.addWidget(self.countdown_radio)
        mode_layout.addWidget(self.specific_radio)
        main_layout.addLayout(mode_layout)
        
        # 倒计时设置
        countdown_layout = QVBoxLayout()
        
        time_inputs_layout = QHBoxLayout()
        
        # 天
        day_layout = QVBoxLayout()
        self.day_input = QLineEdit("0")
        self.day_input.setFixedWidth(40)
        self.day_input.setAlignment(Qt.AlignCenter)
        day_label = QLabel("天")
        day_label.setAlignment(Qt.AlignCenter)
        day_layout.addWidget(self.day_input)
        day_layout.addWidget(day_label)
        
        # 时
        hour_layout = QVBoxLayout()
        self.hour_input = QLineEdit("0")
        self.hour_input.setFixedWidth(40)
        self.hour_input.setAlignment(Qt.AlignCenter)
        hour_label = QLabel("时")
        hour_label.setAlignment(Qt.AlignCenter)
        hour_layout.addWidget(self.hour_input)
        hour_layout.addWidget(hour_label)
        
        # 分
        minute_layout = QVBoxLayout()
        self.minute_input = QLineEdit("30")
        self.minute_input.setFixedWidth(40)
        self.minute_input.setAlignment(Qt.AlignCenter)
        minute_label = QLabel("分")
        minute_label.setAlignment(Qt.AlignCenter)
        minute_layout.addWidget(self.minute_input)
        minute_layout.addWidget(minute_label)
        
        # 秒
        second_layout = QVBoxLayout()
        self.second_input = QLineEdit("0")
        self.second_input.setFixedWidth(40)
        self.second_input.setAlignment(Qt.AlignCenter)
        second_label = QLabel("秒")
        second_label.setAlignment(Qt.AlignCenter)
        second_layout.addWidget(self.second_input)
        second_layout.addWidget(second_label)
        
        time_inputs_layout.addLayout(day_layout)
        time_inputs_layout.addLayout(hour_layout)
        time_inputs_layout.addLayout(minute_layout)
        time_inputs_layout.addLayout(second_layout)
        time_inputs_layout.addStretch()
        
        countdown_layout.addLayout(time_inputs_layout)
        main_layout.addLayout(countdown_layout)
        
        # 指定时间设置
        specific_layout = QHBoxLayout()
        specific_layout.addWidget(QLabel("关机时间:"))
        
        # 年月日
        self.date_input = QLineEdit(datetime.now().strftime("%Y-%m-%d"))
        self.date_input.setFixedWidth(90)
        specific_layout.addWidget(self.date_input)
        
        # 时分
        self.time_input = QLineEdit(datetime.now().strftime("%H:%M"))
        self.time_input.setFixedWidth(50)
        specific_layout.addWidget(self.time_input)
        
        specific_layout.addStretch()
        main_layout.addLayout(specific_layout)
        
        # 当前状态显示
        self.status_label = QLabel("未设置关机计划")
        self.status_label.setAlignment(Qt.AlignCenter)
        self.status_label.setFont(normal_font)
        main_layout.addWidget(self.status_label)
        
        # 按钮
        buttons_layout = QHBoxLayout()
        
        self.start_button = QPushButton("设置关机")
        self.cancel_button = QPushButton("取消关机")
        
        self.start_button.clicked.connect(self.start_shutdown)
        self.cancel_button.clicked.connect(self.cancel_shutdown)
        
        buttons_layout.addWidget(self.start_button)
        buttons_layout.addWidget(self.cancel_button)
        
        main_layout.addLayout(buttons_layout)
        
        # 初始化计时器
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_status)
        self.shutdown_time = None
        
        # 用于保存上一次的显示状态
        self.was_visible = True
        
        # 初始化
        self.mode_group.buttonClicked.connect(self.toggle_input_mode)
        self.toggle_input_mode()
    
    def toggle_input_mode(self):
        # 启用/禁用相应的输入框
        is_countdown = self.countdown_radio.isChecked()
        
        self.day_input.setEnabled(is_countdown)
        self.hour_input.setEnabled(is_countdown)
        self.minute_input.setEnabled(is_countdown)
        self.second_input.setEnabled(is_countdown)
        
        self.date_input.setEnabled(not is_countdown)
        self.time_input.setEnabled(not is_countdown)
    
    def start_shutdown(self):
        try:
            if self.countdown_radio.isChecked():
                # 倒计时模式
                days = int(self.day_input.text())
                hours = int(self.hour_input.text())
                minutes = int(self.minute_input.text())
                seconds = int(self.second_input.text())
                
                total_seconds = days * 86400 + hours * 3600 + minutes * 60 + seconds
                if total_seconds <= 0:
                    QMessageBox.warning(self, "警告", "请设置大于0的时间")
                    return
                
                self.shutdown_time = datetime.now() + timedelta(seconds=total_seconds)
                # 执行系统关机命令
                subprocess.run(f"shutdown /s /t {total_seconds}", shell=True)
            else:
                # 指定时间模式
                try:
                    date_str = self.date_input.text()
                    time_str = self.time_input.text()
                    
                    # 解析日期时间
                    self.shutdown_time = datetime.strptime(f"{date_str} {time_str}:00", "%Y-%m-%d %H:%M:%S")
                    
                    # 计算与当前时间的差异（秒）
                    time_diff = (self.shutdown_time - datetime.now()).total_seconds()
                    
                    if time_diff <= 0:
                        QMessageBox.warning(self, "警告", "指定的时间必须在当前时间之后")
                        return
                    
                    # 执行系统关机命令
                    subprocess.run(f"shutdown /s /t {int(time_diff)}", shell=True)
                except ValueError:
                    QMessageBox.warning(self, "格式错误", "日期格式应为YYYY-MM-DD，时间格式应为HH:MM")
                    return
            
            # 启动计时器更新状态
            self.timer.start(1000)  # 每秒更新一次
            self.update_status()
            
            # 通知用户
            self.tray_icon.showMessage("定时关机", f"计算机将在 {self.shutdown_time.strftime('%Y-%m-%d %H:%M:%S')} 关机", QSystemTrayIcon.Information, 3000)
        
        except ValueError:
            QMessageBox.warning(self, "输入错误", "请输入有效的数字")
    
    def cancel_shutdown(self):
        # 取消系统关机命令
        subprocess.run("shutdown /a", shell=True)
        
        self.timer.stop()
        self.shutdown_time = None
        self.status_label.setText("关机计划已取消")
        
        # 通知用户
        self.tray_icon.showMessage("定时关机", "关机计划已取消", QSystemTrayIcon.Information, 3000)
    
    def update_status(self):
        if self.shutdown_time:
            remaining = self.shutdown_time - datetime.now()
            
            if remaining.total_seconds() <= 0:
                self.timer.stop()
                self.status_label.setText("计算机即将关机")
                return
            
            # 计算剩余时间
            days, remainder = divmod(int(remaining.total_seconds()), 86400)
            hours, remainder = divmod(remainder, 3600)
            minutes, seconds = divmod(remainder, 60)
            
            time_str = ""
            if days > 0:
                time_str += f"{days}天 "
            if hours > 0 or days > 0:
                time_str += f"{hours}时 "
            if minutes > 0 or hours > 0 or days > 0:
                time_str += f"{minutes}分 "
            time_str += f"{seconds}秒"
            
            self.status_label.setText(f"将在 {time_str} 后关机")
    
    def closeEvent(self, event):
        # 重写关闭事件，实现最小化到托盘
        if self.shutdown_time:
            event.ignore()
            self.hide()
            self.tray_icon.showMessage("定时关机", "程序已最小化到系统托盘", QSystemTrayIcon.Information, 2000)
        else:
            reply = QMessageBox.question(self, '退出确认', '确定要退出吗？',
                                          QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.close_app()
            else:
                event.ignore()
    
    def close_app(self):
        # 如果有关机计划，先取消
        if self.shutdown_time:
            subprocess.run("shutdown /a", shell=True)
        QApplication.quit()
    
    def tray_icon_activated(self, reason):
        # 托盘图标点击事件
        if reason == QSystemTrayIcon.DoubleClick:
            self.show()
            self.activateWindow()

if __name__ == "__main__":
    # 创建应用程序
    app = QApplication(sys.argv)
    
    # 如果没有找到图标文件，则创建一个默认图标
    icon_path = "icon.ico"
    if not os.path.exists(icon_path):
        try:
            import tempfile
            from PIL import Image, ImageDraw
            
            # 创建一个简单的图标
            img = Image.new('RGB', (128, 128), color=(53, 153, 219))
            d = ImageDraw.Draw(img)
            d.ellipse((20, 20, 108, 108), fill=(255, 255, 255))
            d.rectangle((55, 40, 73, 88), fill=(53, 153, 219))
            
            # 保存到程序目录而不是临时文件
            img.save(icon_path, format="ICO")
            
            # 设置图标
            app.setWindowIcon(QIcon(icon_path))
            
        except Exception as e:
            print(f"创建默认图标时出错: {e}")
            # 如果创建图标失败，使用一个空图标
            app.setWindowIcon(QIcon())
    else:
        app.setWindowIcon(QIcon(icon_path))
    
    # 创建窗口
    window = ShutdownTimer()
    window.show()
    
    # 运行应用程序
    sys.exit(app.exec_())
